package cn.taobaoke.restful.controller;

import cn.taobaoke.restful.constant.Constants;
import cn.taobaoke.restful.domain.AdminEntity;
import cn.taobaoke.restful.domain.AgentEntity;
import cn.taobaoke.restful.exception.TBKException;
import cn.taobaoke.restful.service.AdminService;
import cn.taobaoke.restful.service.AgentService;
import cn.taobaoke.restful.service.GlobalConfigService;
import cn.taobaoke.restful.service.InnerAPIService;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import java.io.IOException;
import java.util.Map;

/**
 * AccountController类.
 * +-----------------------------------------------------------------------------------------------+
 * |类名称: AccountController                                                                         |
 * |创建时间: 3/21/17                                                                               |
 * |功能简介:                                                                                       |
 * |参考链接:                                                                                       |
 * +-----------------------------------------------------------------------------------------------+
 *
 * @author luch
 */
@RestController
@RequestMapping("/{domain}/{domainId}/api/accounts")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class AccountController extends BaseController {

    private Logger logger = LogManager.getLogger(AccountController.class);

    @PostMapping("/loginByToken")
    public Result loginByToken(@PathVariable String domain, @PathVariable Long domainId) throws IOException {
        String token = request.getHeader("X-User-Token");
        if (StringUtils.isEmpty(token)) {
            throw new TBKException("[token]不能为空");
        }
        AdminEntity adminEntity = adminService.findByTokenAndDomainId(token, domainId);
        if (adminEntity != null) {
            session.setAttribute(Constants.LoginUser.ADMIN, adminEntity);
            session.removeAttribute(Constants.LoginUser.AGENT);

            Cookie cookie = new Cookie("tbk_user_token", adminEntity.getToken());
            cookie.setMaxAge(60 * 60 * 24 * 360);//保存一年
            cookie.setPath("/");
            response.addCookie(cookie);

            String couponUrl = getAgentCouponUrlSite(domain, domainId, 0l);
            adminEntity.setShortCouponWebsite(couponUrl);

            return new Result(adminEntity);
        }

        AgentEntity agentEntity = agentService.findAgentByTokenAndDomainId(token, domainId);
        if (agentEntity != null) {
            session.setAttribute(Constants.LoginUser.AGENT, agentEntity);

            Cookie cookie = new Cookie("tbk_user_token", agentEntity.getToken());
            cookie.setMaxAge(60 * 60 * 24 * 360);//保存一年
            cookie.setPath("/");
            response.addCookie(cookie);

            String couponUrl = getAgentCouponUrlSite(domain, domainId, agentEntity.getId());
            agentEntity.setShortCouponWebsite(couponUrl);


            session.removeAttribute(Constants.LoginUser.ADMIN);
            return new Result(agentEntity);
        }

        throw new TBKException("登录失败, token错误");
    }


    @PostMapping("/login")
    public Result loginByWeChatOrName(@PathVariable String domain, @PathVariable Long domainId, @RequestBody Map<String, Object> data) throws IOException {
        String username = (String) data.get("username");
        String password = (String) data.get("password");

        logger.info("username => {} password => {}", username, password);

        if (StringUtils.isEmpty(username)) {
            throw new TBKException("用户名[username]不能为空");
        }

        if (StringUtils.isEmpty(password)) {
            throw new TBKException("密码[password]不能为空");
        }


        AdminEntity adminEntity = adminService.loginByWeChatAndPassword(username, password, domainId);
        if (adminEntity != null) {
            session.setAttribute(Constants.LoginUser.ADMIN, adminEntity);
            session.removeAttribute(Constants.LoginUser.AGENT);

            Cookie cookie = new Cookie("tbk_user_token", adminEntity.getToken());
            cookie.setMaxAge(60 * 60 * 24 * 360);//保存一年
            cookie.setPath("/");
            response.addCookie(cookie);

            String couponUrl = getAgentCouponUrlSite(domain, domainId, 0l);
            adminEntity.setShortCouponWebsite(couponUrl);

            return new Result(adminEntity);
        }

        AgentEntity agentEntity = agentService.loginByKeywordAndPassword(username, password, domainId);
        if (agentEntity != null) {
            session.setAttribute(Constants.LoginUser.AGENT, agentEntity);

            Cookie cookie = new Cookie("tbk_user_token", agentEntity.getToken());
            cookie.setMaxAge(60 * 60 * 24 * 360);//保存一年
            cookie.setPath("/");
            response.addCookie(cookie);

            String couponUrl = getAgentCouponUrlSite(domain, domainId, agentEntity.getId());
            agentEntity.setShortCouponWebsite(couponUrl);

            session.removeAttribute(Constants.LoginUser.ADMIN);
            return new Result(agentEntity);
        }

        throw new TBKException("登录失败, 用户名或密码错误");
    }


    private String getAgentCouponUrlSite(String domain, Long domainId, Long agentId) throws IOException {
        Map<String, Object> config = globalConfigService.queryConfig(domainId);
        Map map = (Map) config.get("config");
        String couponUrl = "http://yhq.gittis.co";
        if (map != null && map.containsKey("couponUrl")) {
            couponUrl = (String) map.get("couponUrl");
        }
        // more = '%s/d/%s/p/%s/#' % (wxbot.config['coupon_url'], wxbot.domain, wxbot.agentId )
        String couponWebsite = couponUrl;
        if (agentId != null) {
            couponWebsite = String.format("%s/d/%s/p/%d/#", couponUrl, domain, agentId);
        }
        String couponWebsiteShortLink = innerAPIService.shortLink(couponWebsite);
        return couponWebsiteShortLink;
    }

    @PostMapping("/logout")
    public Result logout(@PathVariable Long domainId) {
        session.removeAttribute(Constants.LoginUser.ADMIN);
        session.removeAttribute(Constants.LoginUser.AGENT);

        if (request.getCookies() != null) {
            for (Cookie cookie : request.getCookies()) {
                if ("tbk_user_token".equals(cookie.getName())) {
                    cookie.setMaxAge(0);//保存一年
                }
            }
        }

        return wrapVoid();
    }

    private final
    @NonNull
    AgentService agentService;

    private final
    @NonNull
    AdminService adminService;


    private final
    @NonNull
    InnerAPIService innerAPIService;

    private final
    @NonNull
    GlobalConfigService globalConfigService;
}
